package org.ytor.core.querygen.support;

import org.springframework.stereotype.Component;
import org.ytor.common.util.Strs;
import org.ytor.core.querygen.AbsWhere;
import org.ytor.core.querygen.token.Token;
import org.ytor.core.sqlflow.builder.support.WhereBuilder;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * created by yangtong on 2025/8/11 14:21:00
 * <br/>
 * in匹配 age_in=1,2,3 -> age in(1,2,3)
 */
@Component
public class InWhere extends AbsWhere {
    @Override
    public Boolean isMatch(Token token) {
        return Strs.isNotEmpty(token.getValue()) && token.getKey().endsWith("_in");
    }

    @Override
    protected WhereBuilder positive(WhereBuilder where, Token token) {
        String key = token.getKey();
        String col = Strs.toUnderline(key.substring(0, key.length() - 3));
        List<Object> values = Arrays.stream(token.getValue().split(","))
                .filter(Strs::isNotEmpty)
                .map(String::trim)
                .collect(Collectors.toList());
        return values.isEmpty() ? where : (WhereBuilder) where.in(col, values);
    }

    @Override
    protected WhereBuilder negate(WhereBuilder where, Token token) {
        String key = token.getKey();
        String col = Strs.toUnderline(key.substring(0, key.length() - 3));
        List<Object> values = Arrays.stream(token.getValue().split(","))
                .filter(Strs::isNotEmpty)
                .map(String::trim)
                .collect(Collectors.toList());
        if (values.isEmpty()) return where;
        // 拼成 NOT IN (?, ?, ...)
        String ph = values.stream().map(v -> "?").collect(Collectors.joining(","));
        return (WhereBuilder) where.expr(col + " NOT IN (" + ph + ")", values.toArray());
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }

    @Override
    public WhereBuilder apply(WhereBuilder where, Token token) {
        return positiveOrNegate(where, token);
    }
}

